import 'package:dss_base/dss_base.dart';
import 'package:dss_base/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

class QRScannerPage extends StatefulWidget {
  const QRScannerPage({super.key});

  @override
  State<QRScannerPage> createState() => _QRScannerPageState();
}

class _QRScannerPageState extends State<QRScannerPage>
    with TickerProviderStateMixin {
  late MobileScannerController _scanController;
  late AnimationController _animationController;
  late Animation<Alignment> _alignment;
  bool _isFlashOn = false;

  final Color _strokeColor = Color(0xFFFF3600);
  final Color _lineColor = Color(0xAFFF3600);

  // 扫描图片中的二维码
  Future<void> _clickGallery() async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? picked = await picker.pickImage(
        source: ImageSource.gallery,
      );

      if (picked == null || picked.path.isEmpty) {
        return;
      }

      // 使用当前扫描控制器对选中图片进行解析
      final BarcodeCapture? capture = await _scanController.analyzeImage(picked.path);

      final List<Barcode> barcodes = capture?.barcodes ?? const [];
      String? code;
      for (final b in barcodes) {
        final String? v = b.rawValue;
        if (v != null && v.isNotEmpty) {
          code = v;
          break;
        }
      }

      if (code == null || code.isEmpty) {
        if (mounted) {
          Toast.show('not_qr_code'.tr);
        }
        return;
      }

      await _scanController.stop();
      if (mounted) {
        NavigatorUtil.back(result: code);
      }
    } catch (e) {
      if (mounted) {
        Toast.show('parse_qr_code_failure'.tr);
      }
    }
  }

  Future<void> _clickFlash() async {
    try {
      await _scanController.toggleTorch();
      setState(() {
        _isFlashOn = !_isFlashOn;
      });
    } on Exception catch (e) {
      Log.e('切换闪光灯失败: $e');
    }
  }

  @override
  void initState() {
    super.initState();
    _scanController = MobileScannerController();
    // 动画控制器
    _animationController = AnimationController(
      duration: Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);

    _alignment =
        Tween<Alignment>(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ).animate(
          CurvedAnimation(
            parent: _animationController,
            curve: Curves.easeInOut,
          ),
        );
  }

  @override
  void dispose() {
    _scanController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget child = MobileScanner(
      controller: _scanController,
      onDetect: (capture) {
        final List<Barcode> barcodes = capture.barcodes;
        for (final barcode in barcodes) {
          final String? code = barcode.rawValue;
          if (code != null) {
            _scanController.stop(); // 停止扫描
            NavigatorUtil.back(result: code);
          }
        }
      },
    );
    Widget stroke = Container(
      width: 250.w,
      height: 250.w,
      margin: EdgeInsets.only(top: 120.w),
      decoration: BoxDecoration(
        border: Border.all(color: _strokeColor, width: 2.w),
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: Stack(
        children: [
          // 扫描动画
          AlignTransition(
            alignment: _alignment,
            child: Container(
              height: 2,
              color: _lineColor,
              margin: EdgeInsets.symmetric(horizontal: 5.w),
            ),
          ),
        ],
      ),
    );
    Widget button = Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(
          child: ContainerX(
            onPressed: _clickFlash,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ImageX(urlOrPath: 'ic_flash.png', width: 40.w, height: 40.w,),
                SizedBox(height: 10.w),
                Text(
                  'flash'.tr,
                  style: TextStyle(fontSize: 14.sp, color: Colors.white),
                ),
              ],
            ),
          ),
        ),
        SizedBox(width: 20.w,),
        Expanded(
          child: ContainerX(
            onPressed: _clickGallery,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ImageX(urlOrPath: 'ic_album.png', width: 40.w, height: 40.w,),
                SizedBox(height: 10.w),
                Text(
                  'album'.tr,
                  style: TextStyle(fontSize: 14.sp, color: Colors.white),
                ),
              ],
            ),
          ),
        ),
      ],
    );
    child = Stack(
      children: [
        child,
        Align(alignment: Alignment.topCenter, child: stroke),
        Positioned(left: 10.w, right: 10.w, bottom: 50.w, child: button),
      ],
    );
    return Scaffold(
      appBar: AppBarX(title: ''),
      body: child,
    );
  }
}
